# -*- coding:utf-8 -*-

import os
import random
import datetime

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DC_PATH = os.path.join(BASE_DIR, "testfile", "districtcode.txt")

class idcard:
    def getValidateCheckout(self,id17):
        '''获得校验码算法'''
        weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]  # 十七位数字本体码权重
        validate = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']  # mod11,对应校验码字符值

        sum = 0
        mode = 0
        for i in range(0, len(id17)):
            sum = sum + int(id17[i]) * weight[i]
        mode = sum % 11
        return validate[mode]

    def getdistrictcode(self):
        with open(DC_PATH) as file:
            data = file.read()
            districtlist = data.split('\n')
        for node in districtlist:
            # print node
            if node[10:11] != ' ':
                state = node[10:].strip()
            if node[10:11] == ' ' and node[12:13] != ' ':
                city = node[12:].strip()
            if node[10:11] == ' ' and node[12:13] == ' ':
                district = node[14:].strip()
                code = node[0:6]
                codelist.append({"state": state, "city": city, "district": district, "code": code})

    def getRandomIdNumber(self,sex=1):
        '''产生随机可用身份证号，sex = 1表示男性，sex = 0表示女性'''
        # 地址码产生
        global codelist
        codelist = []
        if not codelist:
            self.getdistrictcode()
        idNumber = codelist[random.randint(0, len(codelist))]['code']  # 地区项

        # 出生日期码
        start, end = "1960-01-01", "1999-12-30"  # 生日起止日期
        #start, end = "2018-12-26", "2018-12-26"  # 生日起止日期
        days = (datetime.datetime.strptime(end, "%Y-%m-%d") - datetime.datetime.strptime(start, "%Y-%m-%d")).days + 1
        birthDays = datetime.datetime.strftime(
            datetime.datetime.strptime(start, "%Y-%m-%d") + datetime.timedelta(random.randint(0, days)), "%Y%m%d")
        idNumber = idNumber + str(birthDays)
        # 顺序码
        for i in range(2):  # 产生前面的随机值
            n = random.randint(0, 9)  # 最后一个值可以包括
            idNumber = idNumber + str(n)
        # 性别数字码
        sexId = random.randrange(sex, 10, step=2)  # 性别码
        idNumber = idNumber + str(sexId)
        # 校验码
        checkOut = self.getValidateCheckout(idNumber)
        idNumber = idNumber + str(checkOut)
        return idNumber

# 随机生成手机号码
def createPhone():
    prelist = ["130", "134", "138", "150", "152", "157", "182", "183", "185", "186", "188", "170", "178"]
    mobile=random.choice(prelist) + "".join(random.choice("0123456789") for i in range(8))
    return mobile



if __name__=="__main__":
    id=idcard()
    print(createPhone())
    print (id.getRandomIdNumber())


